package servlet;

import entity.Emp;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/11 13:50
 * Version:1.0-SNAPSHOT
 * Description:
 */
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        PrintWriter out = response.getWriter();
        if("/add.emp".equals(path)){
            addEmp(request,response);
        } else if("/findById.emp".equals(path)){
            findById(request,response);
        } else if("/modify.emp".equals(path)){
            modifyEmp(request,response);
        } else if("/delete.emp".equals(path)){
            deleteEmp(request,response);
        } else if("/findAll.emp".equals(path)){
            findAllEmp(request,response);
        } else{
            out.print("<h1 style='color:red;'>当前访问的请求有误,尚未存在该请求的处理</h1>");
        }
    }

    public void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");

        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_emp ")
                    .append("   (name,salary,gender,edu,hobbies)")
                    .append(" values ")
                    .append("   (?,?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));

            ps.executeUpdate();

            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("empMsg","服务器内部异常");
            request.getRequestDispatcher("/ems/addEmp.jsp").forward(request,response);
        }


    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        Emp emp = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs = ps.executeQuery();
            if(rs.next()){
                emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
            }
            request.setAttribute("emp",emp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("/ems/modifyEmp.jsp").forward(request,response);
    }

    public void modifyEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        System.out.println("name:"+name+",salary:"+salary+",gender:"+gender+",edu:"+edu+",hobbies:"+ Arrays.toString(hobbies));

        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?, ")
                    .append("   salary = ?, ")
                    .append("   gender = ?, ")
                    .append("   edu = ?, ")
                    .append("   hobbies = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6,Integer.parseInt(id));

            ps.executeUpdate();

            // 返回员工列表
            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");

        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            ps.executeUpdate();

            // 删除完成之后返回员工列表
            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void findAllEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        List<Emp> emps = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,name,salary")
                    .append(" from t_emp ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emps.add(emp);
            }
            request.setAttribute("emps",emps);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("/ems/empList.jsp").forward(request,response);
    }

}
